package com.example.startscreen;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.Gallery;

public class CustomGallery extends Gallery {
	private boolean running = true;
	private Handler handler;
	int position = 0;
	static boolean right = true;

	public CustomGallery(Context context, AttributeSet attrs) {
		super(context, attrs);
		handler = new Handler();
		postDelayedScrollNext();
	}

	public void postDelayedScrollNext2() {
		
		Runnable runner = new Runnable(){

			public void run() {
					postDelayedScrollNext();
					Log.d("CustomGallery", "dpad RIGHT");
					//onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);


						if (getSelectedItemPosition() == getCount() - 1) {
							right = false;
						}
						if (getSelectedItemPosition() == 0) {
							right = true;
						}
						if (right == true) {
							onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
						} else {
							onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, null);
						}
						//				if (getSelectedItemPosition() == getCount()-1) {
						//					setSelection(0);
						//				}
					
					}
		};
		if (running) {
			handler.postDelayed(runner, 2500);
		}
	}

	public Handler getHandler() {
		return handler;
	}

	public void setHandler(Handler handler) {
		this.handler = handler;
	}

	public boolean isRunning() {
		return running;
	}

	public void setRunning(boolean running) {
		this.running = running;
	}

	public void postDelayedScrollNext() {
		if (running) {

			handler.postDelayed(new Runnable() {

				public void run() {
					if (running) {
						if (running) {
							postDelayedScrollNext();
						}
						Log.d("CustomGallery", "dpad RIGHT");
						//onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);

						if (running) {

							if (getSelectedItemPosition() == 0) {
								right = true;
							}
							if (getSelectedItemPosition() == getCount() - 1) {
								right = false;
							}
							if (right == true) {
								onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
							} else {
								onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, null);
							}
							//				if (getSelectedItemPosition() == getCount()-1) {
							//					setSelection(0);
							//				}

						}
					}else{
						return;
					}
				}
			}, 2500);
		}
	}

	private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) {
		return e2.getX() > e1.getX();
	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
		int kEvent;
		if (isScrollingLeft(e1, e2)) {
			Log.d("CustomGallery", "fling LEFT");
			kEvent = KeyEvent.KEYCODE_DPAD_LEFT;
		} else {
			Log.d("CustomGallery", "fling LEFT");
			kEvent = KeyEvent.KEYCODE_DPAD_RIGHT;
		}
		onKeyDown(kEvent, null);
		return true;
	}

}
